#include <Windows.h>
#include <sstream>
#include <iostream>
#include "displayID.hpp"

//	==========================================================================
//	Defines for logging
//	==========================================================================
// Uncomment the following to disable logging.
//#define NO_LOGGING

#ifdef NO_LOGGING
#define LOG(a) 
#else
#define LOG(a) a
#endif

BOOL CALLBACK MonitorEnumProcEx(
							  HMONITOR hMonitor,  // handle to display monitor
							  HDC hdcMonitor,     // handle to monitor DC
							  LPRECT lprcMonitor, // monitor intersection rectangle
							  LPARAM dwData       // data
							  )
{
	DisplayID* did = (DisplayID*)dwData;
	MONITORINFOEX info;
	info.cbSize = sizeof(info);
	GetMonitorInfo(hMonitor, &info);
	
	Monitor mon;
	mon.m_uWidth = info.rcMonitor.right - info.rcMonitor.left;
	mon.m_uHeight = info.rcMonitor.bottom - info.rcMonitor.top;
	mon.m_sName = info.szDevice;

	//did->m_Monitors.push_back(mon);

	return TRUE;
}

bool DisplayID::GetInfo( void )
{
	m_Monitors.clear();

/*
	int numMon = GetSystemMetrics(SM_CMONITORS);
	EnumDisplayMonitors(0,0,&MonitorEnumProcEx, (DWORD)this);
*/

	DISPLAY_DEVICE display;
	display.cb = sizeof(DISPLAY_DEVICE);

	int adapterID = 0;
	LOG(std::cout << "\n\n\n" << std::endl;)
	while( EnumDisplayDevices(NULL, adapterID, &display, 0) )
	{
		std::string adaptername = display.DeviceName;

		int i=0;
		LOG(std::cout << "adapter " << adapterID << std::endl;)
		while(EnumDisplayDevices(adaptername.c_str(), i, &display, 0))
		{
			HDC hDC = CreateDC(TEXT("DISPLAY"), TEXT(display.DeviceString),NULL,NULL);//GetDC(0);
			Monitor mon;

			mon.m_uWidth		= GetDeviceCaps(hDC,HORZRES);
			mon.m_uHeight		= GetDeviceCaps(hDC,VERTRES);
			mon.m_uBits			= GetDeviceCaps(hDC,BITSPIXEL);
			mon.m_uRefresh		= GetDeviceCaps(hDC,VREFRESH);
			mon.m_sName = display.DeviceString;

			LOG(std::cout << "\nMonitor " << i;)
			LOG(std::cout << "\nWidth:                    " << mon.m_uWidth;)
			LOG(std::cout << "\nHeight:                   " << mon.m_uHeight;)
			LOG(std::cout << "\nBits:                     " << mon.m_uRefresh << std::endl;)

			m_Monitors.push_back(mon);

			DeleteDC(hDC);

			++i;
		}

		++adapterID;
	}
	
	return true;
}

std::string DisplayID::Print( void )
{
	std::ostringstream out("\n\n");

	std::vector<Monitor>::const_iterator iter(m_Monitors.begin());
	std::vector<Monitor>::const_iterator end(m_Monitors.end());
	unsigned i=0;
	while(iter!=end)
	{
		out << "\nMonitor " << i;
		out << "\nName:                     " << iter->m_sName;
		out << "\nWidth:                    " << iter->m_uWidth;
		out << "\nHeight:                   " << iter->m_uHeight;
		out << "\nBits:                     " << iter->m_uBits;
		out << "\nRefresh rate:             " << iter->m_uRefresh << " Hz";

		++iter;
		++i;
	}

	return out.str();
}
